<?php namespace App\Http\Controllers\Api;

use App\Department;
use App\Doctors;
use App\DoctorTime;
use App\DoctorWeek;
use App\Exceptions\DataException;
use App\Exceptions\SecurityException;
use App\Files;
use App\Images;
use App\Orders;
use App\Questions;
use App\Referral;
use App\Services\FileManager;
use App\Services\Tools;
use App\Services\UserManager;
use App\Services\Wechat\WechatLogin;
use App\Services\Wechat\WechatModelMsg;
use App\User;
use App\UserInfo;
use Endroid\QrCode\QrCode;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Input;
use \App\Exceptions\NotFoundException;
use Log;

class DoctorController extends ApiController
{
    public function setUserInfo(Request $request,Guard $guard){
        $id           = !is_null(Input::get('id')) ? Input::get('id') : 0;
        $name         = Input::get('name');
        $photo        = Input::get('photo');
        $subject      = Input::get('subject'); //科室
        $station      = Input::get('station'); //职称
        $introduction = Input::get('introduction'); //简介

//        $diplomaId    = $request->get('diploma_id');//证书id
        $fee          = Input::get('fee');
        $feeFace      = $request->get('fee_face');
        $hostpitalId  = $request->get('hospital_id');
        $notice       = $request->get('notice');
        $wxPhotoId    = $request->get('wx_photo');
        $phone        = $request->get('phone');
        $sex          = $request->get('sex');
        $dep_id       = Input::get('dep_list');

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user) {
            throw new SecurityException(SecurityException::LoginFirst);
        }

        if(!preg_match("/^(1[34578])[0-9]{9}$/", trim($phone)))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        $thatDoctor = Doctors::whereId($id)->whereUserId($user->id)->first();

        $isPhone = Doctors::wherePhone($phone)->first();

        if($isPhone && ($thatDoctor && $thatDoctor->id != $isPhone->id))
            return response()->json(['level' => 'error','message' => '该手机号已被他人使用']);

        if(!$thatDoctor){
            if($isPhone)
                return response()->json(['level' => 'error','message' => '该手机号已被他人使用']);

            $thatDoctor = new Doctors();
            $thatDoctor->user_id = $user->id;
        }

        if(!is_null($name))$thatDoctor->doc_name = $name;
//        if(!is_null($photo))$thatDoctor->doc_img = $photo;
        if(!is_null($subject))$thatDoctor->subject = $subject;
        if(!is_null($station))$thatDoctor->station = $station;
        if(!is_null($introduction))$thatDoctor->introduction = $introduction;
        if(!is_null($fee))$thatDoctor->fee = $fee;
        if(!is_null($feeFace))$thatDoctor->fee_face = $feeFace;
//        if(!is_null($diplomaId))$thatDoctor->diploma_id = $diplomaId;
        if(!is_null($hostpitalId))$thatDoctor->hospital_id = $hostpitalId;
        if(!is_null($phone))$thatDoctor->phone = $phone;
        if(!is_null($sex))$thatDoctor->sexual = $sex;
        if(!is_null($dep_id))$thatDoctor->dep_id = $dep_id;
        if(!is_null($notice))$thatDoctor->notice = $notice;

        if(!is_null($wxPhotoId) && $wxPhotoId != ''){
            $accessToken = WechatLogin::getWechatAccessTokenBySecret();

            $headImgUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$accessToken->getAccessToken()."&media_id=".$wxPhotoId;

            Log::error('111111===>'.$headImgUrl);

            /** @var Files $fileModel */
            $fileModel = FileManager::saveFileByWechatHeaderImg($headImgUrl,$wxPhotoId);
            if($fileModel){
                $imageModel = Images::whereFileId($fileModel->id)->first();
                if(!$imageModel){
                    $imageModel = new Images();
                    $imageModel->file_id = $fileModel->id;
                    $imageModel->img_name= 'wechat_img';
                    $imageModel->img_type= $fileModel->file_type;
                    $imageModel->save();

                    $thatDoctor->doc_img = $imageModel->id;
                }
            }
        }elseif((is_null($wxPhotoId) || $wxPhotoId == '') && !is_null($photo) && $photo != 0 && $photo != ''){
            $thatDoctor->doc_img = $photo;
        }


        if($thatDoctor->qrcode_id == 0){

            $ticketCode = WechatLogin::getQrcode($thatDoctor->user_id);
            $photoUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticketCode);
            $fileModel = FileManager::saveFileByQrcodeImg($photoUrl);
            $imageModel = new Images();
            $imageModel->file_id = $fileModel->id;
            $imageModel->img_name = $fileModel->file_name;
            $imageModel->img_type = $fileModel->file_type;
            $imageModel->save();

            $thatDoctor->qrcode_id = $imageModel->id;
        }

        $thatDoctor->save();

        return $this->buildResponse(trans('设置成功'),$thatDoctor);
    }

    public function setWorkTime(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */

        $day     = $request->get('day');
        $am     = $request->get('am');
        $pm     = $request->get('pm');
        $type    = !is_null($request->get('type'))?$request->get('type'):'appoint';

        $weekNum = Tools::getWeekNum(strtotime($day));

        if(!is_null($am) || !is_null($pm)){
            /** @var DoctorTime $thatDateOne */
            $thatDateOne = DoctorTime::whereType($type)->whereUserId($user->id)->whereDays($day)->first();
            if(!$thatDateOne){
                $thatDateOne = new DoctorTime();
                $thatDateOne->user_id = $user->id;
            }

            if(!is_null($type))$thatDateOne->type = $type;
            if(!is_null($day))$thatDateOne->days = $day;
            if($am !== '')$thatDateOne->am = $am;
            if($pm !== '')$thatDateOne->pm = $pm;
            $thatDateOne->save();

            $thatWeek = DoctorWeek::whereUserId($user->id)->whereType($type)->whereWeek($weekNum)->first();
            if(!$thatWeek){
                $thatWeek = new DoctorWeek();
                $thatWeek->user_id = $user->id;
            }

            if(!is_null($type))$thatWeek->type = $type;
            if(!is_null($day))$thatWeek->week = $weekNum;
            if($am !== '')$thatWeek->am = $am;
            if($pm !== '')$thatWeek->pm = $pm;
            $thatWeek->save();

            if($type == 'appoint'){
                /** @var DoctorTime $hasFaceTime */
                $hasFaceTime = DoctorTime::whereType('face')->whereUserId($user->id)->whereDays($day)->first();
                if($hasFaceTime){
                    if($am !== '' && $hasFaceTime->am == 1){
                        $hasFaceTime->am = 0;
                        $hasFaceTime->save();
                    }else if($pm !== '' && $hasFaceTime->pm == 1){
                        $hasFaceTime->pm = 0;
                        $hasFaceTime->save();
                    }
                }

                /** @var DoctorWeek $hasWeekTime */
                $hasWeekTime = DoctorWeek::whereType('face')->whereUserId($user->id)->whereWeek($weekNum)->first();

                if($hasWeekTime){
                    if($am !== '' && $hasWeekTime->am == 1){
                        $hasWeekTime->am = 0;
                        $hasWeekTime->save();
                    }else if($pm !== '' && $hasWeekTime->pm == 1){
                        $hasWeekTime->pm = 0;
                        $hasWeekTime->save();
                    }
                }
            }


        }

        return $this->buildResponse(trans('设置成功'));
    }

    public function setWorkLimit(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */

        $num     = $request->get('num');
        $amount  = $request->get('amount');
        $type    = !is_null($request->get('type'))?$request->get('type'):'appoint';

        if($type == 'appoint'){
            /** @var Doctors $thatDoctor */
            $thatDoctor = Doctors::whereUserId($user->id)->first();
            if(!$thatDoctor)
                throw new NotFoundException(NotFoundException::UserNotFound);

            if(!is_null($num))$thatDoctor->appoint_num = $num;
            if(!is_null($amount))$thatDoctor->fee      = $amount;
            $thatDoctor->save();
        }else{
            /** @var Doctors $thatDoctor */
            $thatDoctor = Doctors::whereUserId($user->id)->first();
            if(!$thatDoctor)
                throw new NotFoundException(NotFoundException::UserNotFound);

            if(!is_null($num))$thatDoctor->face_num     = $num;
            if(!is_null($amount))$thatDoctor->fee_face  = $amount;
            $thatDoctor->save();
        }

        return $this->buildResponse(trans('设置成功'));
    }

    public function answerQuestion(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */

        $qid    = $request->get('q_id');
        $answer = $request->get('answer');

        if(mb_strlen($answer) < 6 || mb_strlen($answer)>250)
            throw new DataException(DataException::AnswerIsTosloft);

        /** @var Questions $thatQuestion */
        $thatQuestion = Questions::whereId($qid)->first();

        if(!$thatQuestion)
            throw new NotFoundException(NotFoundException::DataNotFound);

        $thatQuestion->answer = $answer;
        $thatQuestion->answer_time = date('Y-m-d H:i:s',time());
        $thatQuestion->save();

        WechatModelMsg::sendAnswerMsgToUser($thatQuestion,route('M.Home.newShowAnswer').'?q_id='.$thatQuestion->id);

        return $this->buildResponse(trans('回答成功'),$thatQuestion);
    }

    public function checkDoctor(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        if($user->role < 3)
            throw new SecurityException(SecurityException::NoPermission);

        $docId = $request->get('id');
        $check = !is_null($request->get('check'))?$request->get('check'):0;

        /** @var Doctors $doc */
        $doc = Doctors::whereUserId($docId)->first();
        if(!$doc)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $doc->is_work =  $check;
        $doc->save();

        $thatUser = User::whereId($doc->user_id)->first();

        if($check == 1){
            $thatUser->role = 1;
            $thatUser->save();
        }
        return $this->buildResponse(trans('设置成功'),$doc);
    }

    public function docQrcode(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */

        $qrCode = new QrCode();
        $qrCode
            ->setText(route('Api.User.followDocByQrcode').'?doc_id='.$user->id)
            ->setSize(250)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
            ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ;

        // now we can directly output the qrcode
        header('Content-Type: '.$qrCode->getContentType());
        $qrCode->render();

        // or create a response object
        $response = new Response($qrCode->get(), 200, ['Content-Type' => $qrCode->getContentType()]);

        return $response;
    }

    public function getDepartmentByHospitalId(Request $request){
        $id = $request->get('id');

        $departments = Department::whereHospitalId($id)->get();

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$departments]);
    }

    public function getDoctorByDepId(Request $request){
        $id = $request->get('id');

        $doctors = Doctors::whereDepId($id)->get();

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$doctors]);
    }

    /**
     * 发起转诊
     */
    public function buildReferral(Request $request,Guard $guard){
        /** @var User $user */
        $docUser = UserManager::isLogin($request);
        if(!$docUser)
            return response()->json(['level'=>'error','message'=>'未登录不允许访问']);

        /** @var User $docUser */

        $userId   = $request->get('user_id');
        $docId    = $request->get('doc_id');
        $desc     = $request->get('desc');
        $realname = $request->get('realname');
        $phone    = $request->get('phone');

        /** @var Doctors $thatDoctor */
        $thatDoctor = Doctors::whereId($docId)->first();
        if(!$thatDoctor)
            return response()->json(['level'=>'error','message'=>'当前医生不存在！']);

        /** @var User $thatUser */
        $thatUser = User::whereId($userId)->first();
        if(!$thatUser)
            return response()->json(['level'=>'error','message'=>'当前病人不存在！']);

        $thatUserInfo = UserInfo::whereUserId($thatUser->id)->first();
        if(!$thatUserInfo)
            return response()->json(['level'=>'error','message'=>'当前病人信息不存在！']);

        $thatUserInfo->realname = $realname;
        $thatUserInfo->phone    = $phone;
        $thatUserInfo->save();

        $newReferral = new Referral();
        $newReferral->user_id      = $thatUser->id;
        $newReferral->d_user_id    = $docUser->id;
        $newReferral->dr_user_id   = $thatDoctor->id;
        $newReferral->patient_desc = $desc;
        $newReferral->amount       = 10;
        $newReferral->save();

        /** @var Doctors $selfDoctor */
        $selfDoctor = Doctors::whereUserId($docUser->id)->first();
        if(!$selfDoctor)
            return response()->json(['level'=>'error','message'=>'当前医生不存在！']);

        //发送模版消息推送
        WechatModelMsg::sendReferralsMsgToDoctor($newReferral,$selfDoctor->hospital_id,route("M.Doctor.confirmReferral")."?referral_id=".$newReferral->id);

        return response()->json(['level'=>'success','message'=>'发起转诊成功','data'=>$newReferral]);
    }

    public function confirmReferral(Request $request,Guard $guard){
        $referralId = $request->get('referral_id');
        $reason     = $request->get('reason');
        $status     = $request->get('status');

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'未登录不允许访问']);

        /** @var User $user */

        if($user->role == 0){
            return response()->json(['level'=>'error','message'=>'非医生不允许访问']);
        }

        /** @var Referral $thatReferral */
        $thatReferral = Referral::whereId($referralId)->whereDrUserId($user->id)->first();

        if(!$thatReferral){
            return response()->json(['level'=>'error','message'=>'当前转诊信息不存在']);
        }

        $thatReferral->reason = $reason;
        $thatReferral->status = $status;
        $thatReferral->save();

        if($status==2){
            WechatModelMsg::sendPayMsgToUser($thatReferral,route("M.Home.referralPay")."?referral_id=".$thatReferral->id);
            WechatModelMsg::sendComfirmMsgToDoctor($thatReferral);
        }

        return response()->json(['level'=>'success','message'=>'完成确认',"data"=>$thatReferral]);
    }

    public function setReferralAmount(Request $request,Guard $guard){
        $amount     = $request->get('amount');
        $referralId = $request->get('referral_id');

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if($user->role == 0)
            return response()->json(['level'=>'error','message'=>'无权限访问']);

        
    }

    public function sendMsg(Request $request){
        $openid = $request->get('openid');

        $a = WechatModelMsg::sendReferralsMsgToDoctor($openid);

        var_dump($a) ;
    }
}